package com.healthyeating.manage.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.healthyeating.common.utils.SecurityUtils;
import com.healthyeating.manage.domain.Activity;
import com.healthyeating.manage.domain.Food;
import com.healthyeating.manage.domain.Message;
import com.healthyeating.manage.domain.Recipe;
import com.healthyeating.manage.domain.vo.MessageVo;
import com.healthyeating.manage.mapper.ActivityMapper;
import com.healthyeating.manage.mapper.FoodMapper;
import com.healthyeating.manage.mapper.MessageMapper;
import com.healthyeating.manage.mapper.RecipeMapper;
import com.healthyeating.manage.service.IMessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class MessageServiceImpl implements IMessageService {

    @Autowired
    private FoodMapper foodMapper;

    @Autowired
    private RecipeMapper recipeMapper;

    @Autowired
    private MessageMapper messageMapper;

    @Autowired
    private ActivityMapper activityMapper;

    /**
     * 查询私信
     * @param role
     * @return
     */
    @Override
    public List<MessageVo> list(String role) {
        // 查询私信
        Message message = new Message();
        message.setUserId(SecurityUtils.getUserId());
        message.setIsShow("Y");
        List<Message> messages = messageMapper.selectMessageList(message);
        return addInfos(messages, role);
    }

    /**
     * 新增信息
     * @param message
     * @return
     */
    @Override
    public int insertMessage(Message message) {
        message.setIsShow("Y");
        message.setIsRead("N");
        return messageMapper.insertMessage(message);
    }

    /**
     * 修改信息
     * @param message
     * @return
     */
    @Override
    public int updateMessage(Message message) {
        return messageMapper.updateMessage(message);
    }

    /**
     * 批量修改私信
     * @param messages
     * @return
     */
    @Override
    public int batchUpdateMessage(List<Message> messages) {
        return messageMapper.batchUpdateMessage(messages);
    }

    /**
     * 为私信添加详细信息
     * @param messages
     * @param role
     * @return
     */
    private List<MessageVo> addInfos(List<Message> messages, String role) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        return messages.stream().map(msg -> {
            MessageVo msgVo = new MessageVo();
            BeanUtil.copyProperties(msg, msgVo);
            if (role.equals("admin") || role.equals("commonAdmin") || role.equals("user")) {
                // 查询详细信息
                if (msg.getSource().equals("tb_food")) {
                    Food food = foodMapper.selectFoodByFoodId(msg.getAssociationId());
                    if (food != null) {
                        msgVo.setName(food.getFoodName());
                        // 计算预期过期时间
                        long produceTime = food.getProduceDate().getTime(); // 生产日期的时间戳
                        double shelfLifeDays = food.getShelfLife(); // 保质期，单位：天
                        // 将shelfLifeDays转换为毫秒
                        long shelfLifeMillis = (long) (shelfLifeDays * 24 * 60 * 60 * 1000);
                        Date expireDate = new Date(produceTime + shelfLifeMillis); // 过期日期
                        // 获取当前时间戳
                        long currentTime = System.currentTimeMillis();
                        // 计算剩余时间，以毫秒为单位
                        long leftMillis = expireDate.getTime() - currentTime;
                        // 计算剩余天数和小时数
                        long leftDays = leftMillis / (24 * 60 * 60 * 1000);
                        long leftHours = (leftMillis % (24 * 60 * 60 * 1000)) / (60 * 60 * 1000);
                        // 格式化过期日期
                        String formattedExpireDate = sdf.format(expireDate);
                        // 编辑返回的信息
                        if (leftMillis <= 0) {
                            String info = "您的" + food.getFoodName() + "已经过期了，请及时处理！过期日期：" + formattedExpireDate;
                            msgVo.setInfo(info);
                        } else {
                            String info;
                            if (leftHours == 0) {
                                info = "您的" + food.getFoodName() + "大约还有" + leftDays + "天" + "过期，请及时处理！过期日期：" + formattedExpireDate;
                            } else {
                                info = "您的" + food.getFoodName() + "大约还有" + leftDays + "天" + leftHours + "小时过期，请及时处理！过期日期：" + formattedExpireDate;
                            }
                            msgVo.setInfo(info);
                        }
                    } else {
                        // 从消息集合中去掉这个消息
                        messages.remove(msg);
                    }
                } else if (msg.getSource().equals("tb_activity")) {
                    Activity activity = activityMapper.selectActivityByActivityId(msg.getAssociationId());
                    if (activity != null) {
                        // 编辑返回的信息
                        String info = "您参加的活动：" + activity.getActivityName() + "被管理员清除，已自动退出";
                        msgVo.setInfo(info);
                        msgVo.setName(activity.getActivityName());
                    } else {
                        messages.remove(msg);
                    }
                }
            }
            if (role.equals("admin") || role.equals("commonAdmin") || role.equals("dietitian")) {
               if (msg.getSource().equals("tb_recipe")) {
                   Recipe recipe = recipeMapper.selectRecipeByRecipeId(msg.getAssociationId());
                   if (recipe != null) {
                       // 编辑返回的信息
                       String info = "您推荐的食谱：" + recipe.getRecipeName() + " 已收到用户反馈！";
                       msgVo.setInfo(info);
                       msgVo.setName(recipe.getRecipeName());
                   } else {
                       messages.remove(msg);
                   }
               }
            }
            return msgVo;
        }).collect(Collectors.toList());
    }
}
